package net.aiion.weave.impl.conversions;

import java.util.Collection;
import java.util.Iterator;

import net.aiion.weave.spi.conversions.Converter;
import net.aiion.weave.spi.conversions.ConverterContext;
import net.aiion.weave.spi.conversions.ConverterException;
import net.aiion.weave.spi.naming.Context;

public class ConverterContextImpl implements ConverterContext
{
    private final Iterator<? extends Converter> convertersIterator;

    private final Context context;

    private final Object sourceValue;
    private final Class<?> sourceType;
    private final Class<?> targetType;

    public ConverterContextImpl(final Collection<? extends Converter> aConverters, final Context aNamingContext,
        final Object aSourceValue, final Class<?> aSourceType, final Class<?> aTargetType)
    {
        convertersIterator = aConverters.iterator();

        context = aNamingContext;
        sourceValue = aSourceValue;
        sourceType = aSourceType;
        targetType = aTargetType;
    }

    @Override
    public Context getContext() {
        return context;
    }

    @Override
    public Object getSourceValue() {
        return sourceValue;
    }

    @Override
    public Class<?> getSourceType() {
        return sourceType;
    }

    @Override
    public Class<?> getTargetType() {
        return targetType;
    }

    @Override
    public Object forwardConversion() {
        if (convertersIterator.hasNext()) {
            return convertersIterator.next().convertValue(this);
        }

        throw new ConverterException("There is no converter from " + sourceType + " to " + targetType
            + " registered.");
    }
}
